import pymysql, re


f = open("dict.txt")

db = pymysql.connect(host='localhost', port=3306, user='debian-sys-maint', password='djknQTX2Egm1ZJVq', database='dict', charset='utf8')
cur = db.cursor()

# 数据库操作
# sql = "insert into words (word,mean) values(s%,s%);" # 这个格式不生效
sql = "insert into words (word,mean) values (%s,%s)"
for line in f: # 每次读取一行出来
    # 获取单词和解释
    tup = re.findall(r'(\S+)\s+(.*)',line)[0] # (\S+) 匹配非空字符, \s+ 匹配空格, (.*) 匹配任意字符, 返回列表嵌元组的第一项, 也就是元组,里面有单词和解释
    try:
        cur.execute(sql, tup)
        db.commit()
    except:
        db.rollback()  # 回退到上一次操作
f.close()
cur.close()
db.close()
print("ok")
